<template>
  <p class="login-title">账号注册</p>
  <a-form
    ref="formRef"
    layout="horizontal"
    :model="formState"
    @finish="handleFinish"
    :labelCol="{ span: 4 }"
  >
    <FormItem
      v-for="item in registryForm"
      :key="item.key"
      v-model:formState="formState[item.key || '']"
      :form-item-config="item"
      :rules="rules"
    />
    <a-form-item class="login-button">
      <a-button size="large" block type="primary" html-type="submit">
        注册
      </a-button>
      <p class="extra">
        已有账号？<a-button type="link" @click="$emit('backToLogin')"
          >点击登录</a-button
        >
      </p>
    </a-form-item>
  </a-form>
</template>
<script lang="ts" setup>
import { reactive, ref, watch } from "vue";
import { registryForm } from "./config";
import FormItem from "@/components/Form/FormItem.vue";
import { Rule } from "ant-design-vue/es/form/interface";
import { message } from "ant-design-vue";
import { register } from "@/api";
const emit = defineEmits<{ backToLogin: [] }>();
const formRef = ref();
const formState = reactive<
  {
    email?: string;
    pwd?: string;
    confirmPwd?: string;
    name?: string;
    phone?: string;
    companyName?: string;
    companyType?: string;
    companyAddress?: string;
    professionalField?: string;
    credentials?: any[];
    applyPurpose?: string[];
  } & Record<string, any>
>({});
const rules: Record<string, Rule> = {
  email: {
    required: true,
    validator: async (_rule: Rule, value: string) => {
      if (!value) {
        return Promise.reject("邮箱账号必填");
      } else if (
        !/^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/.test(
          value
        )
      ) {
        return Promise.reject("邮箱账号格式不正确");
      }
      return Promise.resolve();
    },
  },
  confirmPwd: {
    required: true,
    validator: async (_rule: Rule, value: string) => {
      if (!value) {
        return Promise.reject("确认密码必填");
      } else if (value !== formState.pwd) {
        return Promise.reject("与登录密码不一致");
      }
      return Promise.resolve();
    },
  },
};
watch(
  () => [formState.pwd, formState.confirmPwd],
  ([a, b]) => {
    if (a && b) formRef.value.validateFields(["confirmPwd"]);
  }
);
const handleFinish = () => {
  const { credentials, ...rest } = formState;
  register({ ...rest, credentials: credentials?.map((item: any) => item.id) })
    .then(() => {
      message.success("注册成功");
      emit("backToLogin");
    })
    .catch((e) => {
      console.error(e);
      if (!e.message || e.message.startsWith("/api/user/register"))
        message.error("注册失败");
    });
};
</script>
<style lang="scss" scoped>
.verify-code {
  width: calc(100% - 140px);
  margin-right: 30px !important;
}
.extra {
  text-align: center;
}
</style>
